<!doctype html>
<html >
<head lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0 shrink-to-fit=no">
    <title>私信</title>
    <link rel="stylesheet" type="text/css" href="/js/bootstrap/css/bootstrap.min.css" />
    <link rel="stylesheet" type="text/css" href="/js/plugins/chat/normalize.css" />
    <link rel="stylesheet" type="text/css" href="/js/plugins/chat/default.css">
    <link rel="stylesheet" type="text/css" href="/js/plugins/chat/styles.css">
    <script src="/js/plugins/chat/jquery.min.js"></script>
    <script src="/js/bootstrap/js/bootstrap.js"></script>
    <script src="/js/plugins/jrender/jrender.min.js"></script>
    <link rel="stylesheet" href="/js/plugins/dialog2/dialog.css">
    <script src="/js/plugins/dialog2/dialog.min.js"></script>
    <script src="/js/common.js"></script>
    <script src="/js/plugins/jquery-form/jquery.form.js"></script>

</head>
<body style="height: auto">

<div class="col">

</div>
<div id="chatbox">

    <div id="friendslist">
        <div id="topmenu">
            <span class="friends">
                <!--返回上一页-->
                <div>
                <a href="/mine/message.html">
                    <span><i class="fa fa-chevron-left" ></i></span>
                </a>
                </div>
            </span>
            <span class="chats"></span>
            <span class="history"></span>
        </div>

        <div id="friends" >
            <!--搜索框-->
            <div id="search">
                <input type="text" id="searchfield" value="Search contacts..." />
            </div>
            <div render-loop="list">
                <div class="friend"><!--好友列表-->
                    <a href="#chatview" render-fun="setHref" render-key="list.id">
                    <img render-src="list.headImgUrl" />
                    <p>
                        <strong render-html="list.nickName"></strong>
                        <span render-html="list.email"></span>
                    </p>
                    <div class="status available"></div>
                    </a>
                </div>
            </div>
        </div>
    </div>
    <!--聊天界面-->
    <div id="chatview" class="p1">
        <div id="profile">
            <!--关闭按钮-->
            <div id="close">
                <div class="cy"></div>
                <div class="cx"></div>
            </div>
            <!--用户信息-->
            <p>Miro Badev</p>
            <span>miro@badev@gmail.com</span>
        </div>
        <!--聊天内容-->
        <div id="chat-messages">
            <label>Thursday 02</label>
            <form id="chatForm" action="/chat" method="post">
                <input type="hidden" id="id" name="id"/>
                <input type="hidden" id="sendId" name="send.id"/>
                <input type="hidden" id="acceptId" name="accept.id"/>
               <!-- <div render-loop="list">
                <div class="message left">
                    <img render-src="list.accept.headImgUrl" />
                    <div class="bubble" render-html="list.content">
                        Really cool stuff!
                        <div class="corner"></div>
                        <span>3 min</span>
                    </div>
                </div>

                <div class="message right">
                    <img render-src="list.send.headImgUrl" />
                    <div class="bubble" render-html="list.content">
                        Can you share a link for the tutorial?
                        <div class="corner"></div>
                        <span>1 min</span>
                    </div>
                </div>
                </div>-->
                <div id="sendmessage">
                    <input type="text" id="content" name="content" value="Send message..." />
                    <button id="send" type="button" class="sendBtn ">发送</button>
                </div>
            </form>
        </div>
    </div>
</div>


<script>
    $(document).ready(function () {//当DOM载入就绪可以查询及操纵时绑定一个要执行的函数,相当于window.reload()
        var preloadbg = document.createElement('img');
        preloadbg.src = '/img/chat/timeline1.png';//设置背景图片
        $('#searchfield').focus(function () {//当元素获得焦点时，触发 focus 事件
            if ($(this).val() == 'Search contacts...') {
                $(this).val('');
            }
        });
        $('#searchfield').focusout(function () {//当元素失去焦点时触发 focusout 事件
            if ($(this).val() == '') {
                $(this).val('Search contacts...');
            }
        });
        $('#sendmessage input').focus(function () {
            if ($(this).val() == 'Send message...') {
                $(this).val('');
            }
        });
        $('#sendmessage input').focusout(function () {
            if ($(this).val() == '') {
                $(this).val('Send message...');
            }
        });
        //---------------------------------------------
        var user = JSON.parse(sessionStorage.getItem("user"));
        if (user.id) {
            $.get("/chat/friends", {userId: user.id}, function (data) {
                //console.log(data);
                //渲染数据
                $('#friendslist').renderValues(data, {
                    setHref: function (ele, value) {
                        $(ele).attr("href", $(ele).attr("href") + value);
                    }
                });

                //--------------------------------------------
                var temp = 1;//临时变量
                $('.friend').click(function () {
                    //点击获取a元素中的href
                    var hrefStr = $(this).find("a").attr("href");
                    //切割href字符串获取id值,返回一个数组
                    var hrefArr = hrefStr.split("#chatview");
                    //console.log(hrefArr[1]);//获取到id值
                    $.get("/users/" + hrefArr[1], function (data) {
                        $("#profile p").html(data.nickName);//回显昵称
                        $("#profile span").html(data.email);//回显邮箱
                    })

                    var html = '';//回复的div
                    var time = '';//聊天记录时间
                    var text = '';

                    //第一次点击聊天
                    if (temp == 1) {
                        //查询回复信息
                        //跳转页面查询发送信息,第一次查询,回显
                        $.get("/chat", {sendId: user.id, acceptId: hrefArr[1]}, function (data) {
                            console.log(data);
                            if (data.list != null) {
                                //alert(1)
                                $.each(data.list, function (index, ele) {
                                    if (ele.send.id == user.id) {//判断发送人是否为登录用户
                                        html += '<div class="message right">' +
                                            '<img src="' + ele.send.headImgUrl + '" />' +
                                            '<div class="bubble">' + ele.content +
                                            '<div class="corner"></div>' +
                                            '<span>1 min</span>' +
                                            '</div>' +
                                            '</div>';
                                        time = ele.chatTime;
                                    } else {
                                        html += '<div class="message left">' +
                                            '<img src="' + ele.send.headImgUrl + '" />' +
                                            '<div class="bubble">' + ele.content +
                                            '<div class="corner"></div>' +
                                            '<span>3 min</span>' +
                                            '</div>' +
                                            '</div>';
                                    }

                                })
                                $("#sendmessage").before(html);
                                $("#chat-messages label").html(time);
                            }
                        })

                        //发送消息
                        $("#send").click(function () {

                            $('#sendId').val(user.id);//设置发送人id
                            $('#acceptId').val(hrefArr[1]);//设置回复人id
                            //console.log($("#sendmessage input[name='content']").val());
                            $("#chatForm").ajaxSubmit(function (data) {
                                if (data.success) {
                                    var content = $("#sendmessage input[name='content']").val();
                                    $.get("/users/" + user.id, function (data) {
                                        //console.log(data);
                                        if(data.id==user.id){
                                            text = '<div class="message right">' +
                                                '<img src="' + data.headImgUrl + '" />' +
                                                '<div class="bubble">' + content +
                                                '<div class="corner"></div>' +
                                                '<span>1 min</span>' +
                                                '</div>' +
                                                '</div>';
                                        }
                                        $("#sendmessage").before(text);
                                    })
                                    $("#sendmessage input[name='content']").val('');//清空输入框
                                }
                            })
                            websocket.send($("#content").val());
                        })







                        //点击发送,提交表单
                       /* $("#send").click(function () {
                            $('#sendId').val(user.id);//设置发送人id
                            $('#acceptId').val(hrefArr[1]);//设置回复人id
                            //console.log($("#sendmessage input[name='content']").val());
                            $("#chatForm").ajaxSubmit(function (data) {
                                if (data.success) {
                                    var content = $("#sendmessage input[name='content']").val();
                                    $.get("/users/" + user.id, function (data) {
                                        //console.log(data);
                                        if(data.id==user.id){
                                            text = '<div class="message right">' +
                                                '<img src="' + data.headImgUrl + '" />' +
                                                '<div class="bubble">' + content +
                                                '<div class="corner"></div>' +
                                                '<span>1 min</span>' +
                                                '</div>' +
                                                '</div>';
                                        }
                                        $("#sendmessage").before(text);
                                    })
                                    $("#sendmessage input[name='content']").val('');//清空输入框
                                }
                            })

                        })*/


                        var websocket = null;
                        //判断当前浏览器是否支持WebSocket
                        if ('WebSocket' in window) {
                            websocket = new WebSocket("ws://localhost:8080/websocket");
                        }
                        else {
                            alert('当前浏览器 Not support websocket')
                        }

                        //连接发生错误的回调方法
                        websocket.onerror = function () {
                            setMessageInnerHTML("WebSocket连接发生错误");
                        };

                        //连接成功建立的回调方法
                        websocket.onopen = function () {
                            setMessageInnerHTML("WebSocket连接成功");
                        }

                        //接收到消息的回调方法
                        websocket.onmessage = function (event) {
                            setMessageInnerHTML(event.data);
                        }

                        //连接关闭的回调方法
                        websocket.onclose = function () {
                            setMessageInnerHTML("WebSocket连接关闭");
                        }

                        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
                        window.onbeforeunload = function () {
                            closeWebSocket();
                        }

                        //将消息显示在网页上
                        function setMessageInnerHTML(content) {

                                $.get("/users/" + hrefArr[1], function (data) {
                                    if(data){
                                        var html = '<div class="message left">' +
                                            '<img src="' + data.headImgUrl + '" />' +
                                            '<div class="bubble">' + content +
                                            '<div class="corner"></div>' +
                                            '<span>3 min</span>' +
                                            '</div>' +
                                            '</div>';
                                    }
                                    $("#sendmessage").before(html);
                                })

                        }

                        //关闭WebSocket连接
                        function closeWebSocket() {
                            websocket.close();
                        }


                    }


                    temp += 1;





                    //--------------------------------------------
                    var childOffset = $(this).offset();//获取当前元素相对left或top的位移
                    var parentOffset = $(this).parent().parent().parent().offset();
                    var childTop = childOffset.top - parentOffset.top;//定位到当前元素的高度
                    var clone = $(this).find('img').eq(0).clone();//eq(index) 获取第n个元素,获取克隆后图片
                    var top = childTop + 12 + 'px';//设置高度
                    $(clone).css({'top': top}).addClass('floatingImg').appendTo('#chatbox');//设置图片放置top
                    setTimeout(function () {
                        $('#profile p').addClass('animate');//animate() 方法执行 CSS 属性集的自定义动画
                        $('#profile').addClass('animate');
                    }, 100);
                    setTimeout(function () {
                        $('#chat-messages').addClass('animate');
                        $('.cx, .cy').addClass('s1');
                        setTimeout(function () {
                            $('.cx, .cy').addClass('s2');
                        }, 100);
                        setTimeout(function () {
                            $('.cx, .cy').addClass('s3');
                        }, 200);
                    }, 150);
                    $('.floatingImg').animate({
                        'width': '70px',
                        'left': '181px',
                        'top': '20px'
                    }, 200);

                    $('.message').not('.right').find('img').attr('src', $(clone).attr('src'));
                    $('#friendslist').fadeOut();//改变不透明度,达到淡出效果
                    $('#chatview').fadeIn();//淡入效果
                    $('#close').unbind('click').click(function () {//删除元素的绑定事件
                        $('#chat-messages, #profile, #profile p').removeClass('animate');
                        $('.cx, .cy').removeClass('s1 s2 s3');
                        $('.floatingImg').animate({
                            'width': '40px',
                            'top': top,
                            'left': '12px'
                        }, 200, function () {
                            $('.floatingImg').remove();
                        });
                        setTimeout(function () {
                            $('#chatview').fadeOut();
                            $('#friendslist').fadeIn();
                        }, 50);
                    });

                });
            })
        }
        //---------------------------end-------------------------------
       /* var websocket = null;
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://localhost:8080/websocket");
        }
        else {
            alert('当前浏览器 Not support websocket')
        }

        //连接发生错误的回调方法
        websocket.onerror = function () {
            setMessageInnerHTML("WebSocket连接发生错误");
        };

        //连接成功建立的回调方法
        websocket.onopen = function () {
            setMessageInnerHTML("WebSocket连接成功");
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            setMessageInnerHTML(event.data);
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            setMessageInnerHTML("WebSocket连接关闭");
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            closeWebSocket();
        }

        //将消息显示在网页上
        function setMessageInnerHTML(content) {
            $('.friend').click(function () {
                var hrefStr = $(this).find("a").attr("href");
                //切割href字符串获取id值,返回一个数组
                var hrefArr = hrefStr.split("#chatview");
                $.get("/users/" + hrefArr[1], function (data) {
                    if(data){
                        var html = '<div class="message left">' +
                            '<img src="' + data.headImgUrl + '" />' +
                            '<div class="bubble">' + content +
                            '<div class="corner"></div>' +
                            '<span>3 min</span>' +
                            '</div>' +
                            '</div>';
                    }
                    $("#sendmessage").before(html);
                })
            })

        }

        //关闭WebSocket连接
        function closeWebSocket() {
            websocket.close();
        }*/

        //发送消息
       /* $("#send").click(function () {
            websocket.send($("#content").val());
        })*/

        //------------------end----------------------
        /*var currentPage = 1;
        var dataList = [];
        var totalPage;
        goPage();

        function goPage() {
            $.get("/chat/friends", function (data) {
                if (data) {
                    dataList = $.merge(dataList, data.list);
                    $(".friends").renderValues({list:dataList}, {
                        setHref: function (item, value) {
                            /!*$(item).attr("href",$(item).attr("href")+value);*!/
                            var href = $(item).attr("href");
                            $(item).attr("href", href + value);
                        }
                    });
                }
                currentPage += 1;
                totalPage = data.pages;
            }, "json");
        }

        $(window).scroll(function () {
            if ($(window).height() + $(window).scrollTop() >= $(document).height()) {
                if (currentPage <= totalPage) {
                    console.log("翻页");
                    goPage();
                }
            }
            if ($(window).height() + $(window).scrollTop() + 1 >= $(document).height() & currentPage > totalPage) {
                $(document).dialog({
                    type: 'notice',
                    infoText: '到底啦，扑街仔！',
                    autoClose: 2500,
                    position: 'bottom'  // center: 居中; bottom: 底部
                });
            }
        })*/
        //---------------------end----------------
    });
</script>
</body>
</html>